package com.innotek.testworkstation.util;

import com.alibaba.fastjson.JSONObject;

import java.io.*;
import java.net.URI;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 * 字符串工具类
 *
 * @author wangj
 */

public class StringUtils {

    /**
     * 判断集合是否为空
     * @param array
     * @return
     */
    public static boolean isEmpty(Collection<?> array){
        return array==null || array.size()<1;
    }

    /**
     * 判断数组是否为空
     * @param array
     * @return
     */
    public static boolean isEmpty(Object[]array){
        return array==null || array.length<1;
    }

    /**
     * 判断字符串是否为空或null
     * @param input
     *            给定的字符串
     * @return 如果字符串为空或null，返回true，否则返回false
     */
    public static boolean isEmpty(String input) {
        return input == null || input.trim().equals("");
    }

    /**
     * 清除 null 对象
     *
     * @param obj
     * @return
     */
    public static Object clearNull(Object obj) {

        Object returnStr = null;
        if (obj == null) {
            returnStr = (Object) ("");
        } else {
            returnStr = obj;
        }
        return returnStr;
    }

    public static boolean isNotBlank(String input) {
        return !isEmpty(input);
    }

    /**
     * 清除 null 对象
     *
     * @param obj
     * @return String
     */
    public static String clearNullString(Object obj) {

        if ("null".equals(obj)) {
            return "";
        } else {
            return clearNull(obj).toString();
        }
    }

    /**
     * 判断字符串是否符合给定的正则表达式
     * @param input
     *            给定的字符串
     * @param regex
     *            给定的正则表达式
     * @return 如果input符合给定的正则表达式，则返回true，否则返回false
     */
    public static boolean isMatches(String input, String regex) {
        if (input == null)
            return false;
        return input.matches(regex);
    }

    /**
     * 判断端口号合法
     *
     * @param input
     * @return
     */
    public static boolean isPort(String input) {
        String regx = "[1-9]\\d{1,3}";
        return isMatches(input, regx);
    }

    /**
     * 判断IP地址合法
     *
     * @param input
     * @return
     */
    public static boolean isIp(String input) {

        Pattern pattern = Pattern
                .compile("\\b((?!\\d\\d\\d)\\d+|1\\d\\d|2[0-4]\\d|25[0-5])\\.((?!\\d\\d\\d)\\d+|1\\d\\d|2[0-4]\\d|25[0-5])\\.((?!\\d\\d\\d)\\d+|1\\d\\d|2[0-4]\\d|25[0-5])\\.((?!\\d\\d\\d)\\d+|1\\d\\d|2[0-4]\\d|25[0-5])\\b");
        if (input == null)
            return false;
        return pattern.matcher(input).matches();
    }

    /**
     * 获得唯一id
     *
     * @return 18位数字
     */
    public static String getOnlyID() {
        String strRnd;
        double dblTmp;
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
        dblTmp = Math.random() * 100000;
        while (dblTmp < 1000) {
            dblTmp = Math.random() * 100000;
        }
        strRnd = String.valueOf(dblTmp).substring(0, 4);
        String s = df.format(new Date()) + strRnd;
        return s;
    }


    /**
     * 车牌正则表达式
     *
     * @param plateNo
     * @return
     */
    public static boolean isNormalPlateNo(String plateNo) {
        if (plateNo == null) {
            return false;
        }
        // String reg = "^[\u4e00-\u9fa5][A-Za-z](-)?[A-HJ-NP-Za-hj-np-z0-9]{5}[\u4e00-\u9fa5]?$";
        String reg = "^[\u4e00-\u9fa5]{1}[A-Z]{1}[A-Z0-9]{4}[A-Z0-9挂学警港澳空使领]{1}$";
        return Pattern.compile(reg).matcher(plateNo).matches();
    }

    /**
     * 验证手机号码
     *
     * @param mobile
     *            手机号码字符串
     * @return
     */
    @Deprecated
    public static boolean isMobileNumber(String mobile) {
        return isMobileNumber(mobile,null);
    }

    public static boolean isMobileNumber(String mobile,String mobile_format){
        // 从后台获取全局参数；验证手机号正则表达式
        if (StringUtils.isEmpty(mobile_format)) {
            mobile_format = "^(13[0-9]|15[0-9]|17[0-9]|18[0-9]|14[0-9])[0-9]{8}$";
        }
        Pattern p = Pattern.compile(mobile_format);
        return p.matcher(mobile).matches();
    }

    /**
     * 获取uri的参数，以map形式返回
     *
     * @param uri
     * @return
     */
    public static Map<String, String> getURIParams(URI uri) {

        Map<String, String> map = new HashMap<String, String>();
        String[] params = uri.getQuery().split("&");
        if (params.length != 0) {
            for (String param : params) {
                map.put(param.split("=")[0], param.split("=")[1]);
            }
        }
        return map;
    }

    /**
     * 把英文数字替换成中文数字
     *
     * @param input
     * @return
     */
    public static String ToDBC(String input) {

        if (isEmpty(input))
            return "";

        char[] c = input.toCharArray();
        for (int i = 0; i < c.length; i++) {
            if (c[i] == 32) {
                c[i] = (char) 12288;
                continue;
            }

            if (c[i] > 32 && c[i] < 127)
                c[i] = (char) (c[i] + 65248);
        }
        return new String(c);
    }

    /**
     * 清理null字符串数值
     *
     * @Title: clearNullstr
     * @param @param strs
     * @param @return 设定文件
     * @return String[] 返回类型
     * @throws
     */
    public static String[] clearNullstr(String[] strs) {
        for (int i = 0; i < strs.length; i++) {
            strs[i] = clearNullString(strs[i]);
        }
        return strs;
    }

    /****
     * 判断是否是数字
     *
     * @param str
     * @return
     */
    public static boolean isNumber(String str) {
        if (!isNotBlank(str)) {
            return true;
        }
        Pattern pattern = Pattern
                .compile("[0-9]*");
        java.util.regex.Matcher match = pattern.matcher(str);
        if (match.matches() == false) {
            return false;
        } else {
            return true;
        }
    }

    // 给车牌插入 "·"
    public static String insertCenterPoint(String str) {
        try{
            if("-".equals(str))
                return str;
            StringBuilder sb = new StringBuilder(str);
            sb.insert(2, "·");
            return sb.toString();
        }catch (Exception e){
            //LogUtil.e(e.getMessage(),e);
        }
        return str;

    }

    // 半角字符与全角字符转换
    public static String charDBC(String input) {
        char[] c = input.toCharArray();
        for (int i = 0; i < c.length; i++) {
            if (c[i] == 12288) {
                c[i] = (char) 32;
                continue;
            }
            if (c[i] > 65280 && c[i] < 65375)
                c[i] = (char) (c[i] - 65248);
        }
        return new String(c);
    }

    /**
     * <pre>
     * String to Integer
     * </pre>
     *
     * @param value
     * @param def
     * @return int
     */
    public static int toInt(String value, int def) {
        try {
            return Integer.parseInt(value);
        } catch (Exception e) {
        }
        return def;
    }

    public static double toDouble(String str) {
        try {
            return Double.parseDouble(str);
        } catch (Exception e) {
        }
        return 0.00d;
    }

    private static long lastClickTime;

    public synchronized static boolean isFastClick() {
        long time = System.currentTimeMillis();
        if (time - lastClickTime < 500) {
            return true;
        }
        lastClickTime = time;
        return false;
    }

    /**
     * 折扣计算
     *
     * @param sale
     * @return
     */
    public static String saleCalculate(String sale) {
        try {
            double d = Double.parseDouble(sale) / 10.0;
            return d + "";
        } catch (Exception e) {
        }
        return "";
    }

    /**
     * 取金钱的整数
     *
     * @param toChangePrice
     * @return
     */
    public static String priceChangeForInt(String toChangePrice) {
        try {
            toChangePrice = toChangePrice.replace("-", "");
            int index = toChangePrice.indexOf(".");
            if (index != -1) {
                toChangePrice = toChangePrice.substring(0, index);
            }
            long tempPrice = Long.valueOf(toChangePrice);
            long price = tempPrice % 100;
            if (price == 0) {
                return (tempPrice / 100) + "";
            } else if (price < 10) {// 两位小数
                return (tempPrice / 100) + ".0" + price;
            } else {
                return (tempPrice / 100) + "." + price;
            }
        } catch (Exception e) {
        }
        return "";
    }

    /**
     * modify by jxx
     *
     * @param toChangePrice
     * @return
     */
    public static String priceChange(String toChangePrice) {

        try {
            toChangePrice = toChangePrice.replace("-", "");

            int index = toChangePrice.indexOf(".");

            if (index != -1) {
                toChangePrice = toChangePrice.substring(0, index);
            }

            long tempPrice = Long.valueOf(toChangePrice);

            long price = tempPrice % 100;

            StringBuilder sb = new StringBuilder();

            if (price < 10) {
                sb.append(tempPrice / 100).append(".0").append(price);
                return sb.toString();
            }

            sb.append(tempPrice / 100).append(".").append(price);
            return sb.toString();
        } catch (Exception e) {
            return "0";
        }
    }


    /**
     * encoded in utf-8
     *
     * <pre>
     * utf8Encode(null)        =   null
     * utf8Encode("")          =   "";
     * utf8Encode("aa")        =   "aa";
     * </pre>
     * @param str
     * @return
     * @throws UnsupportedEncodingException if an error occurs
     */
    public static String utf8Encode(String str) {
        if (!isEmpty(str) && str.getBytes().length != str.length()) {
            try {
                return URLEncoder.encode(str, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                //LogUtil.e("UnsupportedEncodingException occurred. "+e.getMessage());
            }
        }
        return str;
    }

    /**
     * encoded in utf-8, if exception, return defultReturn
     * @param str
     * @param defultReturn
     * @return
     */
    public static String utf8Encode(String str, String defultReturn) {
        if (!isEmpty(str) && str.getBytes().length != str.length()) {
            try {
                return URLEncoder.encode(str, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                //LogUtil.e("UnsupportedEncodingException occurred. "+e.getMessage());
                return defultReturn;
            }
        }
        return str;
    }

    /**
     * 判断兑换码是否有效
     * @param redeemCode
     * @return true 有效
     */
    public static boolean isVisbiledRedeemCode(String redeemCode){
        if(redeemCode==null || redeemCode.length()<1){
            return false;
        }
        Pattern pattern = Pattern.compile("[a-zA-Z0-9\\u4e00-\\u9fa5]+");
        return pattern.matcher(redeemCode).matches();
    }

    /**
     * 获得时间时分秒
     *
     * @return
     */
    public static String getTimeStr() {

        SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
        String s = df.format(new Date());
        return s;
    }

    /**
     * 获得时间时分秒
     *
     * @return
     */
    public static String getTimeStr(String format) {

        SimpleDateFormat df = new SimpleDateFormat(format);
        String s = df.format(new Date());
        return s;
    }

    public static boolean isNullOrEmpty(String contact) {
        return isEmpty(contact);
    }

    public static long toLong(String fee) {
        try{
            return Long.parseLong(fee);
        }catch (Exception e){

        }
        return 0L;

    }

    /**
     * 判断是不是json格式的字符串
     * @param content
     * @return true是json格式
     */
    public static boolean isJson(String content){
        try {
            JSONObject.parseObject(content);
            return true;
        }catch (Exception e){
            return false;
        }
    }

    /**
     * 通过正则表达式获取第一个匹配到的值
     * @param pattern 正则表达式
     * @param str 字符串
     * @return 匹配的到的值，没有匹配到则返回null
     */
    public static String regexForOne(String pattern, String str){
        Pattern r = Pattern.compile(pattern);
        Matcher m = r.matcher(str);
        if(m.find()){
            return m.group(1);
        }else{
            return null;
        }
    }

    /**
     * 对象的深拷贝（比如HASHMAP）
     * @param obj
     * @param <T>
     * @return
     */
    @SuppressWarnings("unchecked")
    public static <T extends Serializable> T clone(T obj) {
        T cloneObj = null;
        ObjectOutputStream oos = null;
        ObjectInputStream ois = null;
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            oos = new ObjectOutputStream(baos);
            oos.writeObject(obj);

            ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
            ois = new ObjectInputStream(bais);
            cloneObj = (T) ois.readObject();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (oos != null) {
                try {
                    oos.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (ois != null) {
                try {
                    ois.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return cloneObj;
    }
}
